package com.hospicpc.demos.utils;


public class RandomNumber {
    private final long twepoch = 1622505600000L; // 设置起始时间戳，这里选择的是2021年6月1日 00:00:00
    private final long workerIdBits = 3L; // 机器ID所占的位数
    private final long maxWorkerId = -1L ^ (-1L << workerIdBits); // 最大机器ID
    private final long sequenceBits = 9L; // 序列号所占的位数
    private final long workerIdShift = sequenceBits; // 机器ID左移位数
    private final long timestampLeftShift = sequenceBits + workerIdBits; // 时间戳左移位数
    private final long sequenceMask = -1L ^ (-1L << sequenceBits); // 序列号的掩码

    private long workerId;
    private long sequence = 0L;
    private long lastTimestamp = -1L;

    public RandomNumber(long workerId) {
        if (workerId < 0 || workerId > maxWorkerId) {
            throw new IllegalArgumentException("Worker ID超出范围");
        }
        this.workerId = workerId;
    }

    public synchronized long generateUniqueId() {
        long timestamp = System.currentTimeMillis();

        if (timestamp < lastTimestamp) {
            throw new RuntimeException("系统时钟发生回退，无法生成唯一ID");
        }

        if (timestamp == lastTimestamp) {
            sequence = (sequence + 1) & sequenceMask;
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0L;
        }

        lastTimestamp = timestamp;

        return ((timestamp - twepoch) << timestampLeftShift) |
                (workerId << workerIdShift) |
                sequence;
    }

    private long tilNextMillis(long lastTimestamp) {
        long timestamp = System.currentTimeMillis();
        while (timestamp <= lastTimestamp) {
            timestamp = System.currentTimeMillis();
        }
        return timestamp;
    }
}
